<?php
session_start();

/**
 * @author Sven-Ove Bjerkan
 * @copyright 2008
 *
 * To restrict access to a file, simply include this file
 */

 // Already logged in, get data from session
if (!isset($_GET['logout']) && isset($_SESSION['username']) && isset($_SESSION['password'])) {
	$userName = $_SESSION['username'];
	$password = $_SESSION['password'];
	session_regenerate_id(); // Improved security
}

// Form submitted, get data from POST
else if (isset($_POST['username']) && isset($_POST['password'])) {
	$userName = $_POST['username'];
	$password = md5($_POST['password']);
}

// If either logged in or logging in
if (isset($userName)) {
	require_once('login.class.php');
	$login = new Login();
	$res = $login->checkLogin($userName, $password);

	// If valid login
	if ($res['userID'] > 0) {
		$_SESSION['username'] = $userName;
		$_SESSION['password'] = $password;
		$_SESSION['realname'] = $res['realname'];
	}
	// If not...
	else {
		$logout = true;
	}
}

// Logout
if (isset($_GET['logout']) || isset($logout)) {
	unset($_SESSION['username']);
	unset($_SESSION['password']);
	unset($_SESSION['realname']);

	header('Location: '.$_SERVER['PHP_SELF']);
	die;
}

// Not logged in, and not logging in, then show login-form
if (!isset($_SESSION['username'])) {
		if (!isset($_GET['modalbox'])) {
		require_once('../class/config.class.php');
		echo Config::singleton()->getConf('headerAdmin');
		?>
	
		<form action="" method="POST">
		Brukernavn: <input type="text" name="username"><br />
		Passord: <input type="password" name="password"><br />
		<input type="submit" value="Logg inn">
		</form>
	
		<?php
		echo Config::singleton()->getConf('footer');
		die;
	}
	else {
		header('Location: '.$_SERVER['PHP_SELF']);
		die;
	}
}
?>